package com.example.socket.config;

import com.example.socket.model.MessageDto;
import com.google.gson.Gson;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Created with IDEA
 * author:QinWei
 * Date:2019/5/20
 * Time:10:13
 */


@ServerEndpoint(value = "/websocket/{param}")
@Component
public class MyWebSocket {

    private String username;
    //用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
    private static ConcurrentMap<String, MyWebSocket> users = new ConcurrentHashMap<String, MyWebSocket>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("param") String param) {
        this.session = session;
        webSocketSet.add(this); //加入set中
        username =  param ;
        users.put(username, this);
        System.out.println("有新连接加入！当前在线人数为" + webSocketSet.size());
        this.session.getAsyncRemote().sendText("恭喜您成功连接上WebSocket-->当前在线人数为：" + webSocketSet.size());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this); //从set中删除
        System.out.println("有一连接关闭！当前在线人数为" + webSocketSet.size());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        Gson gson = new Gson();
        MessageDto mes = gson.fromJson(message, MessageDto.class);
        if (mes.getTo() == null) {
            Set<String> key = users.keySet();
            for (String k : key) {
                if (k.equals(mes.from)) {
                    continue;
                }
                users.get(k).sendMessage(message);
            }
        } else {
            MyWebSocket toServlet = users.get(mes.getFrom());
            MyWebSocket toServlet2 = users.get(mes.getTo());
            if (null != toServlet) {
                toServlet.sendMessage(message);
                toServlet2.sendMessage(message);
            }
        }
        //群发消息
        broadcast("用户" + (Integer.parseInt(session.getId()) + 1) + ":&nbsp;&nbsp;&nbsp;" + message);
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 群发自定义消息
     */
    public void broadcast(String message) {
        for (MyWebSocket item : webSocketSet) {
            //同步异步说明参考：http://blog.csdn.net/who_is_xiaoming/article/details/53287691
            //this.session.getBasicRemote().sendText(message);
            item.session.getAsyncRemote().sendText(message);//异步发送消息.
        }
    }

    private void sendMessage(String mes) {
        this.session.getAsyncRemote().sendText(mes);
    }
}


